# 基于Ubuntu 22.04
FROM ubuntu:22.04

# 1. 基础环境配置（非交互模式+时区，避免安装卡顿）
ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=Asia/Shanghai

# 2. 替换apt为阿里云国内源（加速下载）
RUN sed -i s@/archive.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.list && \
    sed -i s@/security.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.list && \
    apt-get clean

# 3. 安装基础依赖（删除libavresample-dev，补充apt-utils）
RUN apt-get update && apt-get upgrade -y && \
    apt-get install -y \
    apt-utils \
    build-essential \
    cmake \
    git \
    wget \
    unzip \
    yasm \
    pkg-config \
    libswscale-dev \
    libtbb2 \
    libtbb-dev \
    libjpeg-dev \
    libpng-dev \
    libtiff-dev \
    libavformat-dev \
    libpq-dev \
    libxine2-dev \
    libglew-dev \
    libtiff5-dev \
    zlib1g-dev \
    libavcodec-dev \
    libavutil-dev \
    libpostproc-dev \
    libgstreamer1.0-dev \
    libgstreamer-plugins-base1.0-dev \
    libgtk-3-dev \
    libv4l-dev \
    libatlas-base-dev \
    gfortran \
    python3-dev \
    python3-pip \
    && rm -rf /var/lib/apt/lists/*

# 4. 配置pip国内源（清华大学，加速Python包安装）
RUN pip3 config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple && \
    pip3 config set global.trusted-host pypi.tuna.tsinghua.edu.cn

# 5. 安装Python依赖（numpy为OpenCV必需）
RUN pip3 install --upgrade pip && \
    pip3 install numpy

# 6. 安装FFmpeg（直接apt安装，兼容系统依赖）
RUN apt-get update && \
    apt-get install -y ffmpeg && \
    rm -rf /var/lib/apt/lists/*

# 7. 编译安装OpenCV 4.8.0（适配Ubuntu 22.04，含contrib扩展）
WORKDIR /tmp
RUN wget -O opencv.zip https://github.com/opencv/opencv/archive/4.8.0.zip && \
    wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/4.8.0.zip && \
    unzip opencv.zip && \
    unzip opencv_contrib.zip && \
    cd opencv-4.8.0 && \
    mkdir -p build && cd build && \
    cmake -D CMAKE_BUILD_TYPE=RELEASE \
          -D CMAKE_INSTALL_PREFIX=/usr/local \
          -D INSTALL_PYTHON_EXAMPLES=ON \
          -D INSTALL_C_EXAMPLES=OFF \
          -D OPENCV_EXTRA_MODULES_PATH=/tmp/opencv_contrib-4.8.0/modules \
          -D PYTHON_EXECUTABLE=/usr/bin/python3 \
          -D WITH_FFMPEG=ON \
          -D BUILD_EXAMPLES=ON .. && \
    make -j$(nproc) && \
    make install && \
    ldconfig && \
    cd / && rm -rf /tmp/*          # 清理临时文件（减小镜像体积）

# 8. 最终配置
WORKDIR /app               
RUN ffmpeg -version && \
    python3 -c "import cv2; print('OpenCV version:', cv2.__version__)"  # 验证OpenCV
